package org.jeecg.modules.xl.store.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.checkerframework.checker.units.qual.A;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.xl.store.entity.XlCustomerMystore;
import org.jeecg.modules.xl.store.entity.XlCustomerStoreInfo;
import org.jeecg.modules.xl.store.service.IXlCustomerMystoreService;
import org.jeecg.modules.xl.store.service.IXlCustomerStoreInfoService;
import org.jeecg.modules.xl.store.vo.XlCustomerStoreImportVO;
import org.jeecg.modules.xl.store.vo.XlCustomerStoreInfoExportVO;
import org.jeecg.modules.xl.store.vo.XlCustomerStoreInfoPage;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @Description: 客户门店信息
 * @Author: jeecg-boot
 * @Date: 2024-10-24
 * @Version: V1.0
 */
@Api(tags = "客户门店信息")
@RestController
@RequestMapping("/xl/xlCustomerStoreInfo")
@Slf4j
public class XlCustomerStoreInfoController {
    @Autowired
    private IXlCustomerStoreInfoService xlCustomerStoreInfoService;
    @Autowired
    private IXlCustomerMystoreService xlCustomerMystoreService;

    /**
     * 分页列表查询
     *
     * @param xlCustomerStoreInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @GetMapping(value = "/list")
    public Result<IPage<XlCustomerStoreInfo>> queryPageList(XlCustomerStoreInfo xlCustomerStoreInfo,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                            HttpServletRequest req) {
        QueryWrapper<XlCustomerStoreInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerStoreInfo, req.getParameterMap());
        Page<XlCustomerStoreInfo> page = new Page<XlCustomerStoreInfo>(pageNo, pageSize);
        IPage<XlCustomerStoreInfo> pageList = xlCustomerStoreInfoService.page(page, queryWrapper);
        return Result.OK(pageList);
    }


    /**
     * 我的门店查询
     *
     * @param xlCustomerStoreInfo
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "客户门店信息-分页列表查询")
    @ApiOperation(value = "我的门店查询", notes = "我的门店查询")
    @GetMapping(value = "/myList")
    public Result<IPage<XlCustomerStoreInfo>> myList(XlCustomerStoreInfo xlCustomerStoreInfo,
                                                     @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                     @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                     HttpServletRequest req) {
        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //当前用户的角色
        String roles = user.getRoleCode();

        boolean isAdmin = false;
        String[] ADMIN_ROLES = {"slt_admin", "admin","HTMDDZY","HTMSHZY"};
        if (StrUtil.containsAny(roles, ADMIN_ROLES)) {
            isAdmin = true;
        }

        QueryWrapper<XlCustomerStoreInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerStoreInfo, req.getParameterMap());
        Page<XlCustomerStoreInfo> page = new Page<XlCustomerStoreInfo>(pageNo, pageSize);

        //如果是管理员或作其他需要查询全部门店的账户，就直接返回全部门店
        if (isAdmin) {
            return Result.OK(xlCustomerStoreInfoService.page(page, queryWrapper));
        } else {
            //查询我的门店
            queryWrapper.eq("user_account", user.getUsername());
            page.setRecords(xlCustomerMystoreService.selectStoresByUserId2(queryWrapper));
            return Result.OK(page);
        }
    }

    /**
     * 添加
     *
     * @param xlCustomerStoreInfoPage
     * @return
     */
    @ApiOperation(value = "客户门店信息-添加", notes = "客户门店信息-添加")
    @RequiresPermissions("org.jeecg.modules.xl:xl_customer_store_info:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody XlCustomerStoreInfoPage xlCustomerStoreInfoPage) {
        XlCustomerStoreInfo xlCustomerStoreInfo = new XlCustomerStoreInfo();
        BeanUtils.copyProperties(xlCustomerStoreInfoPage, xlCustomerStoreInfo);
        xlCustomerStoreInfoService.saveMain(xlCustomerStoreInfo, xlCustomerStoreInfoPage.getXlCustomerMystoreList());
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param xlCustomerStoreInfoPage
     * @return
     */

    @RequiresPermissions("org.jeecg.modules.xl:xl_customer_store_info:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody XlCustomerStoreInfoPage xlCustomerStoreInfoPage) {
        XlCustomerStoreInfo xlCustomerStoreInfo = new XlCustomerStoreInfo();
        BeanUtils.copyProperties(xlCustomerStoreInfoPage, xlCustomerStoreInfo);
        XlCustomerStoreInfo xlCustomerStoreInfoEntity = xlCustomerStoreInfoService.getById(xlCustomerStoreInfo.getId());
        if (xlCustomerStoreInfoEntity == null) {
            return Result.error("未找到对应数据");
        }
        xlCustomerStoreInfoService.updateMain(xlCustomerStoreInfo, xlCustomerStoreInfoPage.getXlCustomerMystoreList());
        return Result.OK("编辑成功!");
    }

    @RequiresPermissions("org.jeecg.modules.xl:xl_customer_store_info:edit")
    @RequestMapping(value = "/editWxbot", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> editWxbot(@RequestBody XlCustomerStoreInfoPage xlCustomerStoreInfoPage) {
        XlCustomerStoreInfo xlCustomerStoreInfo = new XlCustomerStoreInfo();
        xlCustomerStoreInfo.setId(xlCustomerStoreInfoPage.getId());
        xlCustomerStoreInfo.setWxbotAtWxid(xlCustomerStoreInfoPage.getWxbotAtWxid());
        xlCustomerStoreInfo.setWxbotGroupWxid(xlCustomerStoreInfoPage.getWxbotGroupWxid());
        xlCustomerStoreInfoService.updateById(xlCustomerStoreInfo);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "客户门店信息-通过id删除")
    @ApiOperation(value = "客户门店信息-通过id删除", notes = "客户门店信息-通过id删除")
    @RequiresPermissions("org.jeecg.modules.xl:xl_customer_store_info:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        xlCustomerStoreInfoService.delMain(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "客户门店信息-批量删除")
    @ApiOperation(value = "客户门店信息-批量删除", notes = "客户门店信息-批量删除")
    @RequiresPermissions("org.jeecg.modules.xl:xl_customer_store_info:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.xlCustomerStoreInfoService.delBatchMain(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "客户门店信息-通过id查询")
    @ApiOperation(value = "客户门店信息-通过id查询", notes = "客户门店信息-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<XlCustomerStoreInfo> queryById(@RequestParam(name = "id", required = true) String id) {
        XlCustomerStoreInfo xlCustomerStoreInfo = xlCustomerStoreInfoService.getById(id);
        if (xlCustomerStoreInfo == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(xlCustomerStoreInfo);

    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "客户门店工作人员通过主表ID查询")
    @ApiOperation(value = "客户门店工作人员主表ID查询", notes = "客户门店工作人员-通主表ID查询")
    @GetMapping(value = "/queryXlCustomerMystoreByMainId")
    public Result<List<XlCustomerMystore>> queryXlCustomerMystoreListByMainId(@RequestParam(name = "id", required = true) String id) {
        List<XlCustomerMystore> xlCustomerMystoreList = xlCustomerMystoreService.selectByMainId(id);
        return Result.OK(xlCustomerMystoreList);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param xlCustomerStoreInfo
     */
    @RequiresPermissions("org.jeecg.modules.xl:xl_customer_store_info:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, XlCustomerStoreInfo xlCustomerStoreInfo, @RequestParam(required = false) Integer isMy) {
        // Step.1 组装查询条件查询数据
        QueryWrapper<XlCustomerStoreInfo> queryWrapper = QueryGenerator.initQueryWrapper(xlCustomerStoreInfo, request.getParameterMap());
        //配置选中数据查询条件
        String selections = request.getParameter("selections");
        if (oConvertUtils.isNotEmpty(selections)) {
            List<String> selectionList = Arrays.asList(selections.split(","));
            queryWrapper.in("id", selectionList);
        }

        //当前操作人
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //当前用户的角色
        String roles = user.getRoleCode();

      List<XlCustomerStoreInfo> xlCustomerStoreInfoList = new ArrayList<>();

        //如果是采购主管或作采购导出，就根据mystore中的门店工作人员表进行导出
        if(StrUtil.containsAny(roles, "sltcgzg")||StrUtil.containsAny(roles, "slt_customer")){
            List<XlCustomerStoreInfo> storeInfos  = xlCustomerMystoreService.selectStoresByUserId(user.getId());
            xlCustomerStoreInfoList.addAll(storeInfos);
        }else{
            xlCustomerStoreInfoList.addAll( xlCustomerStoreInfoService.list(queryWrapper)) ;
        }



        // Step.3 组装pageList
        List<XlCustomerStoreInfoExportVO> pageList = new ArrayList<XlCustomerStoreInfoExportVO>();
        for (XlCustomerStoreInfo main : xlCustomerStoreInfoList) {
            XlCustomerStoreInfoExportVO vo = new XlCustomerStoreInfoExportVO();
            BeanUtils.copyProperties(main, vo);
            pageList.add(vo);
        }

        // Step.4 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        mv.addObject(NormalExcelConstants.FILE_NAME, "客户门店信息列表");
        mv.addObject(NormalExcelConstants.CLASS, XlCustomerStoreInfoExportVO.class);
        mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("客户门店信息数据", "导出人:" + user.getRealname(), "客户门店信息"));
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }
    @Autowired
    private ISysUserService sysUserService;
    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("org.jeecg.modules.xl:xl_customer_store_info:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
        for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
            // 获取上传文件对象
            MultipartFile file = entity.getValue();
            ImportParams params = new ImportParams();
            params.setTitleRows(2);
            params.setHeadRows(1);
            params.setNeedSave(false);
            try {
                List<XlCustomerStoreImportVO> list = ExcelImportUtil.importExcel(file.getInputStream(), XlCustomerStoreImportVO.class, params);
                for (XlCustomerStoreImportVO page : list) {
                    XlCustomerStoreInfo po = new XlCustomerStoreInfo();
                    BeanUtils.copyProperties(page, po);
                    //创建
                    List<XlCustomerMystore> xlCustomerMystoreList = new ArrayList<>();
                    XlCustomerMystore mystore = new XlCustomerMystore();
                    //导入的时候，自动创建账号

                    mystore.setUserId(null);
                    mystore.setUserName(page.getStoreManager());
                    mystore.setStoreName(page.getStoreName());
                    mystore.setPhone(page.getStoreManagerPhone());
                    xlCustomerMystoreList.add(mystore);
                    xlCustomerStoreInfoService.saveMain(po, xlCustomerMystoreList);
                }
                return Result.OK("文件导入成功！数据行数:" + list.size());
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                return Result.error("文件导入失败:" + e.getMessage());
            } finally {
                try {
                    file.getInputStream().close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return Result.OK("文件导入失败！");
    }

}
